'''
Encoding converter plugin for gedit application
Copyright (C) 2009  Alexey Kuznetsov <ak@axet.ru>
Copyright (C) 2011  Krzysztof Dryja <cih997@gmail.com>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

----

thx to http://live.gnome.org/Gedit/PythonPluginHowTo

version 3.0.0
'''

from gi.repository import GObject, Gtk, Gdk, Gedit
import os
import sys

from browsedialog import BrowseDialog
from dochelper import DocHelper
from encodingshelper import EncodingsHelper

class EncodingConverterPluginHelper:
  
  window = None
  plugin = None
  action_group = None
  ui_id = None
  data_dir = None

  def __init__(self, plugin, window, data_dir):
    self.window = window
    self.plugin = plugin
    self.data_dir = data_dir

    self.load_menus()

  def load_menus(self):

    manager = self.window.get_ui_manager()

    self._action_group = Gtk.ActionGroup("GeditToUTF8EncodingConverterPluginActions")
    self._action_group.add_actions([("ConvertTextFromAction", None, _("_Convert text from ..."),
                                         None, None,
                                         self.from_browse)])
    

    # UI manager snippet to add menu items to the View menu
    ui_str = """
    <ui>
      <menubar name="MenuBar">
        <menu name="DocumentsMenu" action="Documents">
          <placeholder name="DocumentsOps_2">
            <menuitem name="ConvertTextFrom" action="ConvertTextFromAction"/>"""

    eh = EncodingsHelper()
    encs = eh.gedit_prefs_manager_get_shown_in_menu_encodings()

    for enc in encs:
      action = "from_" + enc.get_charset()
      actions = [(action, None, _("_Convert text from ") + enc.get_charset(), None, None, self.from_encoding)]
      self._action_group.add_actions(actions, (enc))
      ui_str += """<menuitem name='ConvertTextFrom""" + enc.get_charset() + """' action='""" + action + """'/>"""
    
    # Insert the action group
    manager.insert_action_group(self._action_group)
    
    ui_str += """</placeholder>
        </menu>
      </menubar>
    </ui>
    """
    
    # Merge the UI
    self._ui_id = manager.add_ui_from_string(ui_str)

  def close(self):
    manager = self.window.get_ui_manager()
    manager.remove_ui(self._ui_id)
    manager.remove_action_group(self._action_group)
    manager.ensure_update()

    self.action_group = None
    self.window = None
    self.plugin = None

  def update_ui(self):
    doc = self.window.get_active_document()
    self.action_group.set_sensitive(bool(doc and not doc.get_readonly()))

  def from_encoding(self, window, enc):
    doc = DocHelper(self.window.get_active_document())
    doc.recode_doc(enc.get_charset())

  def from_browse(self, widget, window):
    doc1 = self.window.get_active_document()
    bd = BrowseDialog(window, self.plugin, doc1, self.data_dir)
    res = bd["dialog"].run()
    if res == Gtk.ResponseType.OK:
      doc2 = DocHelper(bd.doc2)
      doc = DocHelper(doc1)
      doc.replace_new(doc2.read_all())
